// 沙盘绘制和交互功能
class SandboxCanvas {
    constructor(canvasId) {
        this.canvas = document.getElementById(canvasId);
        this.ctx = this.canvas.getContext('2d');
        this.isDrawing = false;
        this.lastX = 0;
        this.lastY = 0;
        this.brushSize = 5;
        this.opacity = 1;
        this.objects = []; // 存储沙盘对象
        
        this.initCanvas();
        this.bindEvents();
        this.drawGrid();
    }

    initCanvas() {
        // 设置画布尺寸
        this.resizeCanvas();
        window.addEventListener('resize', () => this.resizeCanvas());
        
        // 设置画布样式
        this.ctx.lineCap = 'round';
        this.ctx.lineJoin = 'round';
        this.ctx.globalCompositeOperation = 'source-over';
    }

    resizeCanvas() {
        const rect = this.canvas.parentElement.getBoundingClientRect();
        this.canvas.width = rect.width;
        this.canvas.height = rect.height;
        this.drawGrid();
        this.redrawObjects();
    }

    bindEvents() {
        // 鼠标事件
        this.canvas.addEventListener('mousedown', (e) => this.startDrawing(e));
        this.canvas.addEventListener('mousemove', (e) => this.draw(e));
        this.canvas.addEventListener('mouseup', () => this.stopDrawing());
        this.canvas.addEventListener('mouseout', () => this.stopDrawing());

        // 触摸事件（iPad支持）
        this.canvas.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const mouseEvent = new MouseEvent('mousedown', {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            this.canvas.dispatchEvent(mouseEvent);
        });

        this.canvas.addEventListener('touchmove', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            const mouseEvent = new MouseEvent('mousemove', {
                clientX: touch.clientX,
                clientY: touch.clientY
            });
            this.canvas.dispatchEvent(mouseEvent);
        });

        this.canvas.addEventListener('touchend', (e) => {
            e.preventDefault();
            const mouseEvent = new MouseEvent('mouseup', {});
            this.canvas.dispatchEvent(mouseEvent);
        });

        // 阻止默认的触摸行为
        this.canvas.addEventListener('touchstart', (e) => e.preventDefault());
        this.canvas.addEventListener('touchmove', (e) => e.preventDefault());
        this.canvas.addEventListener('touchend', (e) => e.preventDefault());
    }

    getMousePos(e) {
        const rect = this.canvas.getBoundingClientRect();
        return {
            x: e.clientX - rect.left,
            y: e.clientY - rect.top
        };
    }

    startDrawing(e) {
        this.isDrawing = true;
        const pos = this.getMousePos(e);
        this.lastX = pos.x;
        this.lastY = pos.y;
        
        // 更新坐标显示
        this.updateCoordinates(pos.x, pos.y, '开始绘制');
        
        // 发送WebSocket消息
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.sendMessage({
                type: 'draw_start',
                x: pos.x,
                y: pos.y,
                brushSize: this.brushSize,
                opacity: this.opacity
            });
        }
    }

    draw(e) {
        const pos = this.getMousePos(e);
        
        // 更新坐标显示
        this.updateCoordinates(pos.x, pos.y, this.isDrawing ? '绘制中' : '移动');
        
        if (!this.isDrawing) return;
        
        this.drawLine(this.lastX, this.lastY, pos.x, pos.y);
        
        // 发送WebSocket消息
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.sendMessage({
                type: 'draw_move',
                fromX: this.lastX,
                fromY: this.lastY,
                toX: pos.x,
                toY: pos.y,
                brushSize: this.brushSize,
                opacity: this.opacity
            });
        }
        
        this.lastX = pos.x;
        this.lastY = pos.y;
    }

    stopDrawing() {
        if (!this.isDrawing) return;
        
        this.isDrawing = false;
        
        // 更新坐标显示
        this.updateCoordinates(this.lastX, this.lastY, '结束绘制');
        
        // 发送WebSocket消息
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.sendMessage({
                type: 'draw_end',
                x: this.lastX,
                y: this.lastY
            });
        }
    }

    drawLine(x1, y1, x2, y2) {
        this.ctx.globalAlpha = this.opacity;
        this.ctx.lineWidth = this.brushSize;
        this.ctx.strokeStyle = '#2c3e50';
        
        this.ctx.beginPath();
        this.ctx.moveTo(x1, y1);
        this.ctx.lineTo(x2, y2);
        this.ctx.stroke();
        
        this.ctx.globalAlpha = 1;
    }

    drawGrid() {
        const gridSize = 20;
        this.ctx.strokeStyle = '#e0e0e0';
        this.ctx.lineWidth = 0.5;
        this.ctx.globalAlpha = 0.5;
        
        // 绘制垂直线
        for (let x = 0; x <= this.canvas.width; x += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.canvas.height);
            this.ctx.stroke();
        }
        
        // 绘制水平线
        for (let y = 0; y <= this.canvas.height; y += gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.canvas.width, y);
            this.ctx.stroke();
        }
        
        this.ctx.globalAlpha = 1;
    }

    clear() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.drawGrid();
        this.objects = [];
        
        // 发送清空消息
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.sendMessage({
                type: 'clear_canvas'
            });
        }
    }

    reset() {
        this.clear();
        this.brushSize = 5;
        this.opacity = 1;
        
        // 重置UI控件
        document.getElementById('brush-size').value = 5;
        document.getElementById('opacity').value = 100;
        document.getElementById('brush-size-value').textContent = 5;
        document.getElementById('opacity-value').textContent = '100%';
    }

    setBrushSize(size) {
        this.brushSize = size;
    }

    setOpacity(opacity) {
        this.opacity = opacity / 100;
    }

    updateCoordinates(x, y, action) {
        document.getElementById('coord-x').textContent = Math.round(x);
        document.getElementById('coord-y').textContent = Math.round(y);
        document.getElementById('action-type').textContent = action;
    }

    // 处理来自WebSocket的绘制消息
    handleRemoteDrawing(data) {
        switch (data.type) {
            case 'draw_start':
                // 远程开始绘制，可以显示其他用户的光标
                break;
            case 'draw_move':
                // 绘制远程用户的线条
                const oldBrushSize = this.brushSize;
                const oldOpacity = this.opacity;
                
                this.brushSize = data.brushSize || 5;
                this.opacity = data.opacity || 1;
                
                this.ctx.strokeStyle = '#e74c3c'; // 远程绘制使用红色
                this.drawLine(data.fromX, data.fromY, data.toX, data.toY);
                
                this.brushSize = oldBrushSize;
                this.opacity = oldOpacity;
                break;
            case 'draw_end':
                // 远程结束绘制
                break;
            case 'clear_canvas':
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.drawGrid();
                break;
        }
    }

    redrawObjects() {
        // 重绘所有对象（在画布大小改变时使用）
        this.objects.forEach(obj => {
            // 这里可以添加重绘逻辑
        });
    }

    // 添加沙盘对象（如建筑、道路等）
    addObject(type, x, y, properties = {}) {
        const obj = {
            id: Date.now() + Math.random(),
            type: type,
            x: x,
            y: y,
            ...properties
        };
        
        this.objects.push(obj);
        this.drawObject(obj);
        
        // 发送到服务器
        if (window.websocketManager && window.websocketManager.isConnected()) {
            window.websocketManager.sendMessage({
                type: 'add_object',
                object: obj
            });
        }
        
        return obj;
    }

    drawObject(obj) {
        this.ctx.save();
        
        switch (obj.type) {
            case 'building':
                this.ctx.fillStyle = obj.color || '#3498db';
                this.ctx.fillRect(obj.x - 15, obj.y - 15, 30, 30);
                this.ctx.strokeStyle = '#2c3e50';
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(obj.x - 15, obj.y - 15, 30, 30);
                break;
            case 'tree':
                this.ctx.fillStyle = '#27ae60';
                this.ctx.beginPath();
                this.ctx.arc(obj.x, obj.y, 10, 0, Math.PI * 2);
                this.ctx.fill();
                break;
            case 'road':
                this.ctx.strokeStyle = '#95a5a6';
                this.ctx.lineWidth = 8;
                this.ctx.beginPath();
                this.ctx.moveTo(obj.x, obj.y);
                this.ctx.lineTo(obj.endX || obj.x + 50, obj.endY || obj.y);
                this.ctx.stroke();
                break;
        }
        
        this.ctx.restore();
    }
}

// 导出类供其他文件使用
window.SandboxCanvas = SandboxCanvas;